package com.smart.translator.util;

import android.media.AudioFormat;
import android.media.AudioManager;
// import android.media.AudioTrack; // 注释掉AudioTrack导入
import android.util.Log;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import org.java_websocket.framing.Framedata;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.ByteBuffer;
import java.io.ByteArrayOutputStream;
import java.util.concurrent.LinkedBlockingQueue;
import android.os.Handler;
import android.os.Looper;
import android.content.Context;
import com.smart.translator.data.AppConfig;

public class DoubaoTTSManager {
    private static final String TAG = "DoubaoTTS";
    private static final String WS_PATH = "/ws/doubao_tts";
    private WebSocketClient webSocketClient;
    // private AudioTrack audioTrack; // 注释掉AudioTrack
    private boolean isConnected = false;
    private TTSStateListener stateListener;
    private Context context;
    private AppConfig appConfig;
    
    // ADPCM编码器
    private AdpcmEncoder adpcmEncoder;
    
    // 音频参数
    private static final int SAMPLE_RATE = 8000;
    private static final int CHANNEL_CONFIG = AudioFormat.CHANNEL_OUT_MONO;
    private static final int AUDIO_FORMAT = AudioFormat.ENCODING_PCM_16BIT;
    
    // 连接地址
    private static final String WS_URL = "ws://qixin.yeshan.fun/ws/doubao_tts";
    
    // PCM数据累积缓冲区
    private ByteArrayOutputStream pcmBuffer = new ByteArrayOutputStream();
    private boolean isSynthesisComplete = false;
    
    // BLE发送队列相关
    private LinkedBlockingQueue<byte[]> bleSendQueue = new LinkedBlockingQueue<>(1000000); // 增大队列长度
    private static final int BLE_CHUNK_SIZE = 120; // 每次发送120字节
    private boolean isBleSendTimerRunning = false;
    
    // 当前正在处理的ADPCM数据
    private byte[] currentAdpcmData = null;
    private int currentAdpcmOffset = 0;
    
    // 后台发送线程
    private Thread bleSendThread = null;
    private volatile boolean isBleSendThreadRunning = false;
    
    public interface TTSStateListener {
        void onConnected();
        void onDisconnected();
        void onError(String error);
        void onSynthesisComplete();
    }
    
    // BLE写入回调接口
    public interface BleWriteCallback {
        void onWriteAdpcmData(byte[] adpcmData);
    }
    
    // PCM数据回调接口
    public interface PcmDataCallback {
        void onPcmDataReceived(byte[] pcmData);
    }
    
    private BleWriteCallback bleWriteCallback;
    private PcmDataCallback pcmDataCallback;
    
    public DoubaoTTSManager(Context context) {
        this.context = context;
        loadAppConfig();
        initTTS();
    }
    
    /**
     * 从SharedPreferences加载应用配置
     */
    private void loadAppConfig() {
        try {
            android.content.SharedPreferences prefs = context.getSharedPreferences("app_config", Context.MODE_PRIVATE);
            String serverUrl = prefs.getString("server_url", "qixin.yeshan.fun");
            appConfig = new AppConfig();
            appConfig.setServerUrl(serverUrl);
            Log.d(TAG, "从SharedPreferences加载服务器配置: " + serverUrl);
        } catch (Exception e) {
            Log.e(TAG, "加载配置失败", e);
            // 使用默认配置
            appConfig = new AppConfig();
            appConfig.setServerUrl("qixin.yeshan.fun");
        }
    }
    
    /**
     * 构建WebSocket URL
     */
    private String buildWebSocketUrl() {
        String serverUrl = appConfig != null ? appConfig.getServerUrl() : null;
        if (serverUrl == null || serverUrl.isEmpty()) {
            serverUrl = "qixin.yeshan.fun";
        }
        return "ws://" + serverUrl + WS_PATH;
    }
    
    public void setStateListener(TTSStateListener listener) {
        this.stateListener = listener;
    }
    
    public void setBleWriteCallback(BleWriteCallback callback) {
        this.bleWriteCallback = callback;
    }
    
    public void setPcmDataCallback(PcmDataCallback callback) {
        this.pcmDataCallback = callback;
    }
    
    public void initTTS() {
        try {
            String wsUrl = buildWebSocketUrl();
            URI uri = new URI(wsUrl);
            Log.d(TAG, "初始化TTS WebSocket连接: " + wsUrl);
            webSocketClient = new WebSocketClient(uri) {
                @Override
                public void onOpen(ServerHandshake handshakedata) {
                    isConnected = true;
                    Log.d(TAG, "TTS WebSocket连接成功");
                    if (stateListener != null) {
                        stateListener.onConnected();
                    }
                }

                @Override
                public void onMessage(String message) {
                    Log.d(TAG, "TTS收到文本消息: " + message);
                    if ("[END]".equals(message)) {
                        Log.d(TAG, "TTS合成完成，开始处理完整PCM数据");
                        isSynthesisComplete = true;
                        
                        // 处理完整的PCM数据
                        processCompletePcmData();
                        
                        if (stateListener != null) {
                            stateListener.onSynthesisComplete();
                        }
                    }
                }

                @Override
                public void onMessage(ByteBuffer bytes) {
                    byte[] audioData = new byte[bytes.remaining()];
                    bytes.get(audioData);
                    Log.d(TAG, "TTS收到音频数据: " + audioData.length + " 字节");
                    
                    // 打印PCM数据内容（前20字节）
                    if (audioData.length > 0) {
                        StringBuilder sb = new StringBuilder();
                        for (int i = 0; i < Math.min(20, audioData.length); i++) {
                            sb.append(String.format("%02X ", audioData[i]));
                        }
                        Log.d(TAG, "TTS PCM数据(前20字节): " + sb.toString());
                    }
                    
                    // 注释掉播放音频数据，只发送到BLE设备
                    // playAudioData(audioData);
                    
                    // 回调PCM数据
                    if (pcmDataCallback != null) {
                        pcmDataCallback.onPcmDataReceived(audioData);
                    }
                    
                    // 累积PCM数据到缓冲区
                    try {
                        pcmBuffer.write(audioData);
                        Log.d(TAG, "累积PCM数据: " + audioData.length + " 字节，总计: " + pcmBuffer.size() + " 字节");
                    } catch (Exception e) {
                        Log.e(TAG, "PCM数据累积异常", e);
                    }
                }

                @Override
                public void onClose(int code, String reason, boolean remote) {
                    isConnected = false;
                    Log.d(TAG, "TTS WebSocket连接关闭: code=" + code + ", reason=" + reason);
                    
                    // 清理WebSocket客户端，避免重用
                    webSocketClient = null;
                    
                    if (stateListener != null) {
                        stateListener.onDisconnected();
                    }
                }

                @Override
                public void onError(Exception ex) {
                    Log.e(TAG, "TTS WebSocket错误: " + ex.getMessage());
                    
                    // 清理WebSocket客户端，避免重用
                    webSocketClient = null;
                    isConnected = false;
                    
                    if (stateListener != null) {
                        stateListener.onError(ex.getMessage());
                    }
                }
            };
            
            // 注释掉AudioTrack初始化，不再需要播放功能
            // initAudioTrack();
            
            // 初始化ADPCM编码器
            initAdpcmEncoder();
            
            // 初始化BLE发送定时器
            initBleSendTimer();
            
        } catch (URISyntaxException e) {
            Log.e(TAG, "TTS URI错误: " + e.getMessage());
            if (stateListener != null) {
                stateListener.onError("URI错误: " + e.getMessage());
            }
        }
    }
    
    /**
     * 处理完整的PCM数据
     */
    private void processCompletePcmData() {
        try {
            byte[] completePcmData = pcmBuffer.toByteArray();
            if (completePcmData.length == 0) {
                Log.w(TAG, "PCM缓冲区为空，跳过处理");
                return;
            }
            
            Log.d(TAG, "=== 开始处理完整PCM数据 ===");
            Log.d(TAG, "完整PCM数据长度: " + completePcmData.length + " 字节");
            
            // 重置编码器状态，确保与测试编码一致
            adpcmEncoder.reset();
            Log.d(TAG, "编码器状态已重置，准备编码完整PCM数据");
            
            // 一次性编码为ADPCM
            byte[] completeAdpcmData = adpcmEncoder.encodeFromBytes(completePcmData);
            Log.d(TAG, "完整ADPCM编码完成: " + completePcmData.length + " -> " + completeAdpcmData.length + " 字节");
            
            // 直接将完整ADPCM数据放入BLE发送队列
            if (!bleSendQueue.offer(completeAdpcmData)) {
                Log.w(TAG, "BLE发送队列已满，丢弃完整ADPCM数据");
            } else {
                Log.d(TAG, "=== 完整ADPCM数据已放入BLE发送队列，长度: " + completeAdpcmData.length + " 字节 ===");
            }
            
            // 启动BLE发送定时器
            startBleSendTimer();
            
            // 清空缓冲区
            pcmBuffer.reset();
            isSynthesisComplete = false;
            
        } catch (Exception e) {
            Log.e(TAG, "处理完整PCM数据异常", e);
        }
    }
    
    private void initAdpcmEncoder() {
        adpcmEncoder = new AdpcmEncoder();
        
        // 测试ADPCM编码
        adpcmEncoder.testEncoding();
        
        Log.d(TAG, "ADPCM编码器初始化完成");
    }
    
    /**
     * 初始化BLE发送定时器
     */
    private void initBleSendTimer() {
        // 只初始化变量，不创建定时器逻辑
        Log.d(TAG, "BLE发送系统初始化完成，块大小: " + BLE_CHUNK_SIZE + " 字节");
    }
    
    /**
     * 启动BLE发送定时器
     */
    private void startBleSendTimer() {
        if (!isBleSendTimerRunning) {
            isBleSendTimerRunning = true;
            
            // 使用后台线程进行BLE发送
            if (bleSendThread == null || !bleSendThread.isAlive()) {
                isBleSendThreadRunning = true;
                bleSendThread = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        // 设置线程优先级为高优先级，提升BLE发送性能
                        android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_URGENT_AUDIO);
                        
                        while (isBleSendThreadRunning) {
                            try {
                                // 处理BLE发送队列
                                processBleSendQueue();
                                
                                // 短暂休眠，避免CPU占用过高
                                Thread.sleep(15); // 减少到15ms，提升发送频率
                                
                            } catch (Exception e) {
                                Log.e(TAG, "BLE发送线程异常", e);
                            }
                        }
                    }
                }, "BLE-Send-Thread");
                
                // 设置线程优先级
                bleSendThread.setPriority(Thread.MAX_PRIORITY);
                bleSendThread.start();
                Log.d(TAG, "启动BLE发送后台线程（高优先级）");
            }
        }
    }
    
    /**
     * 停止BLE发送定时器
     */
    private void stopBleSendTimer() {
        if (isBleSendTimerRunning) {
            isBleSendTimerRunning = false;
            isBleSendThreadRunning = false;
            
            // 停止后台线程
            if (bleSendThread != null && bleSendThread.isAlive()) {
                bleSendThread.interrupt();
                try {
                    bleSendThread.join(1000); // 等待1秒
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
                bleSendThread = null;
            }
            
            Log.d(TAG, "停止BLE发送后台线程");
        }
    }
    
    /**
     * 处理BLE发送队列
     */
    private void processBleSendQueue() {
        try {
            // 如果当前没有正在处理的数据，从队列中取出新的完整ADPCM数据
            if (currentAdpcmData == null) {
                currentAdpcmData = bleSendQueue.poll();
                currentAdpcmOffset = 0;
                
                if (currentAdpcmData == null) {
                    // 队列为空，停止后台线程
                    isBleSendTimerRunning = false;
                    isBleSendThreadRunning = false;
                    Log.d(TAG, "BLE发送队列为空，停止发送后台线程");
                    return;
                }
                
                // 减少日志输出，只在开始时记录一次
                Log.d(TAG, "开始处理ADPCM数据: " + currentAdpcmData.length + " 字节");
            }
            
            // 发送当前ADPCM数据的一个块
            int remainingBytes = currentAdpcmData.length - currentAdpcmOffset;
            int chunkSize = Math.min(BLE_CHUNK_SIZE, remainingBytes);
            
            byte[] chunk = new byte[chunkSize];
            System.arraycopy(currentAdpcmData, currentAdpcmOffset, chunk, 0, chunkSize);
            
            // 减少日志输出，只在每10次发送时记录一次
            if (currentAdpcmOffset % (BLE_CHUNK_SIZE * 10) == 0) {
                Log.d(TAG, "发送ADPCM块: 偏移=" + currentAdpcmOffset + ", 长度=" + chunkSize + " 字节");
            }
            
            if (bleWriteCallback != null) {
                bleWriteCallback.onWriteAdpcmData(chunk);
            }
            
            // 更新偏移量
            currentAdpcmOffset += chunkSize;
            
            // 如果当前数据发送完成，清空当前数据，下次从队列取新的
            if (currentAdpcmOffset >= currentAdpcmData.length) {
                Log.d(TAG, "ADPCM数据发送完成，队列剩余: " + bleSendQueue.size() + " 个数据");
                currentAdpcmData = null;
                currentAdpcmOffset = 0;
            }
            
        } catch (Exception e) {
            Log.e(TAG, "处理BLE发送队列异常", e);
        }
    }
    
    // private void initAudioTrack() {
    //     try {
    //         int bufferSize = AudioTrack.getMinBufferSize(SAMPLE_RATE, CHANNEL_CONFIG, AUDIO_FORMAT);
    //         // audioTrack = new AudioTrack(
    //         //     AudioManager.STREAM_MUSIC,
    //         //     SAMPLE_RATE,
    //         //     CHANNEL_CONFIG,
    //         //     AUDIO_FORMAT,
    //         //     bufferSize,
    //         //     AudioTrack.MODE_STREAM
    //         // );
    //         Log.d(TAG, "TTS AudioTrack初始化成功，缓冲区大小: " + bufferSize);
    //     } catch (Exception e) {
    //         Log.e(TAG, "TTS AudioTrack初始化失败: " + e.getMessage());
    //     }
    // }
    
    public void connect() {
        if (webSocketClient != null && !isConnected) {
            Log.d(TAG, "TTS开始连接WebSocket");
            webSocketClient.connect();
        } else if (isConnected) {
            Log.d(TAG, "TTS WebSocket已连接");
        } else if (webSocketClient == null) {
            // WebSocket客户端为null，需要重新初始化
            Log.d(TAG, "TTS WebSocket客户端为null，重新初始化");
            initTTS();
            if (webSocketClient != null) {
                Log.d(TAG, "TTS重新连接WebSocket");
                webSocketClient.connect();
            }
        } else {
            // 如果WebSocket客户端存在但状态异常，需要重新创建
            Log.d(TAG, "TTS WebSocket状态异常，重新创建连接");
            disconnect();
            // 重新初始化WebSocket客户端
            initTTS();
            // 重新连接
            if (webSocketClient != null) {
                Log.d(TAG, "TTS重新连接WebSocket");
                webSocketClient.connect();
            }
        }
    }
    
    public void synthesizeText(String text) {
        if (isConnected && webSocketClient != null) {
            Log.d(TAG, "TTS发送文本进行合成: " + text);
            
            // 清空PCM缓冲区，准备新的合成
            pcmBuffer.reset();
            isSynthesisComplete = false;
            
            webSocketClient.send(text);
        } else {
            Log.e(TAG, "TTS WebSocket未连接，无法发送文本");
            if (stateListener != null) {
                stateListener.onError("WebSocket未连接");
            }
        }
    }
    
    private void playAudioData(byte[] audioData) {
        // if (audioTrack != null) {
        //     try {
        //         audioTrack.play();
        //         int written = audioTrack.write(audioData, 0, audioData.length);
        //         Log.d(TAG, "TTS播放音频数据: " + written + "/" + audioData.length + " 字节");
        //     } catch (Exception e) {
        //         Log.e(TAG, "TTS播放音频数据失败: " + e.getMessage());
        //     }
        // } else {
        //     Log.e(TAG, "TTS AudioTrack未初始化");
        // }
    }
    
    public void disconnect() {
        Log.d(TAG, "TTS断开连接");
        if (webSocketClient != null) {
            webSocketClient.close();
            webSocketClient = null; // 设置为null避免重用
        }
        // if (audioTrack != null) {
        //     audioTrack.stop();
        //     audioTrack.release();
        //     audioTrack = null;
        // }
        pcmBuffer.reset();
        
        // 停止BLE发送定时器并清空队列
        stopBleSendTimer();
        bleSendQueue.clear();
        currentAdpcmData = null;
        currentAdpcmOffset = 0;
        
        // 确保后台线程已停止
        if (bleSendThread != null && bleSendThread.isAlive()) {
            bleSendThread.interrupt();
        }
        
        isConnected = false;
    }
    
    public boolean isConnected() {
        return isConnected;
    }
    
    public void release() {
        disconnect();
        webSocketClient = null;
        stateListener = null;
        bleWriteCallback = null;
        adpcmEncoder = null;
        
        // 清理BLE发送相关资源
        bleSendQueue = null;
        
        // 清理后台线程（disconnect()中已经处理，这里确保清理）
        if (bleSendThread != null && bleSendThread.isAlive()) {
            bleSendThread.interrupt();
        }
        bleSendThread = null;
    }
    
    /**
     * 获取PCM缓冲区大小
     */
    public int getPcmBufferSize() {
        return pcmBuffer.size();
    }
} 